const _ = require('lodash');
const async = require('async');
const services = require('../../services');

const commonService = services.common;
const adminService = services.admin;

function initPage(req, res, callback) {
  const params = req.query;
  const pageId = params.pageId;
  const { SysRole: roleModel, SysDepartment: departmentModel } = commonService.getModels();
  async.parallel({
    roleList: async.apply(commonService.getList, roleModel),
    departmentList: async.apply(commonService.getList, departmentModel),
    userList: async.apply(adminService.user.getList, params),
    formList: async.apply(adminService.user.getAllEnableForms, params),
    pageTotal: async.apply(adminService.user.getPageTotal, params),
  }, (error, result) => callback(error, _.assign(result, { pageId })));
}

function getList(req, res, callback) {
  const params = req.query;
  const pageId = params.pageId;
  async.parallel({
    userList: async.apply(adminService.user.getList, params),
    pageTotal: async.apply(adminService.user.getPageTotal, params),
  }, (error, result) => callback(error, _.assign(result, { pageId })));
}

function saveDetail(req, res, callback) {
  const { SysUser: userModel, SysUserRoleMapping: userRoleMappingModel } = commonService.getModels();
  const params = req.body;
  params.id = params.id == 0 ? null : params.id;
  params.password = '123456';
  let userIsExist = false;
  const judgeUserIsExist = (next) => {
    userIsExist = false;
    next(null);
  };
  const saveUser = (next) => {
    if (userIsExist) return next(null);
    userModel.upsert(params, next);
  };
  const delRoleMapping = (user, next) => {
    userRoleMappingModel.destroyAll({ userEmployeeId: user.employeeId,
    }, next);
  };
  const saveUserRoleMapping = (user, next) => {
    if (userIsExist) return next(null);
    const userRoleMapping = [];
    _.forEach(params.finalRoleList, roleItem => userRoleMapping.push({ userEmployeeId: params.employeeId, roleId: roleItem.id, others: roleItem.others }));
    userRoleMappingModel.create(userRoleMapping, next);
  };
  async.waterfall([judgeUserIsExist, saveUser, delRoleMapping, saveUserRoleMapping], callback);
}

module.exports = {
  initPage,
  getList,
  saveDetail,
};
